﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PersonalAlbum.Caching;
using MyAlbum.Model;
using MyAlbum.Services;

namespace PersonalAlbum
{

    public class WebCacheManager : ICacheService
    {
        private WebCacheManager() { }
        private static readonly WebCacheManager _instance=new WebCacheManager();
        public static WebCacheManager Instance
        {
            get
            {
                return _instance;
            }
        }
        public object GetData(string key)
        {
            return HttpContext.Current.Items[key];

        }

        public IEnumerable<Section> GetSections()
        {
            IEnumerable<Section> items = WebCacheManager.Instance.GetData("sections") as IEnumerable<Section>;
            if (items == null)
            {
                items = ObjectFactory.GetInstance<ISectionService>().GetItems();
                WebCacheManager.Instance.InsertData("sections", items);
            }
            return items;
        }

        public void InsertData(string key, object value)
        {
            if (HttpContext.Current.Items[key] != null)
            {
                lock (HttpContext.Current.Items)
                {
                    HttpContext.Current.Items[key] = value;
                }
            }
            else
            {
                lock (HttpContext.Current.Items)
                {
                    HttpContext.Current.Items.Add(key, value);
                }
            }
        }

        public void RemoveItem(string key)
        {
            lock (HttpContext.Current.Items)
            {
                HttpContext.Current.Items.Remove(key);
            }
        }

    }
}
